﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Threading;

namespace LaberMediaClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindowLrc : Window
    {
        public MainWindowLrc()
        {
            InitializeComponent();
        }
        private DispatcherTimer timer;
        double mediaLongth;

        string mediaFileName;
        string labelFileName;
        List<string> labels = new List<string>();
        int isTest = 1;
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            mediaElement.LoadedBehavior = MediaState.Manual;
            mediaElement.UnloadedBehavior = MediaState.Manual;
            mediaElement.Volume = 0.5;
            mediaElement.MouseLeftButtonDown += MediaElement_MouseLeftButtonDown;
            //mediaElement.MediaEnded += (sender, e) => myMediaElement.Position = TimeSpan.Zero;
            //mediaElement.me
            this.Title = "LaberMedia";
            if (isTest == 1)
            {
                mediaFileName = @"D:\2topic\创作\汉字经过AI绘画之后全变成了小姐姐！.mp4";
                if(File.Exists(mediaFileName))
                    LoadMedia();
            }
            

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += Timer_Tick;
            timer.Start();
        }

        bool isPlaying = true;
        private void MediaElement_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (mediaElement.Source != null )
            {
                if(isPlaying)
                    mediaElement.Pause();
                else
                    mediaElement.Play();
                isPlaying =!isPlaying;
            }
    
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            if (mediaElement.Source != null&& mediaElement.NaturalDuration.HasTimeSpan)
            {
                progressSlider.Value = mediaElement.Position.TotalSeconds;
                labelTime.Content = string.Format("{0}:{1} / {2}:{3}",
                    Math.Floor(mediaElement.Position.TotalMinutes),
                    mediaElement.Position.Seconds,
                    Math.Floor(mediaElement.NaturalDuration.TimeSpan.TotalMinutes),
                    mediaElement.NaturalDuration.TimeSpan.Seconds
                    );

                //labelTime.Content = string.Format("{0} / {1}",
                //    mediaElement.Position.ToString(@"mm\:ss"),
                //    mediaElement.NaturalDuration.TimeSpan.ToString(@"mm\:ss")
                //    );
            }
        }
        private void buttonOpen_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "所有文件(*.*)|*.*";
            if (openFileDialog.ShowDialog() == true)
            {
                // 获取选中的文件路径
                string filePath = openFileDialog.FileName;
                // 这里可以进行文件路径的进一步处理
                mediaFileName = filePath;
                LoadMedia();

            }
        }

        private void LoadMedia()
        {
            var idx = mediaFileName.LastIndexOf(".");
            if (idx == -1)
                labelFileName = null;
            else
            {
                labelFileName = mediaFileName.Substring(0, idx) + ".txt";
                labels.Clear();
                comboLebal.Items.Clear();
                LoadRecord();
            }
            mediaElement.Source = new Uri(mediaFileName);
            this.Title = "LaberMedia-" + new FileInfo(mediaFileName).Name;
            mediaElement.Play();
        }

        private void LoadRecord()
        {
            if (File.Exists(labelFileName))
            {
                var str = File.ReadAllText(labelFileName);
                listLabelRecord = JsonHelper.ParseJson<List<LabelModel>>(str);
                dataGrid.ItemsSource = listLabelRecord;
                foreach (var item in listLabelRecord)
                {
                    if (labels.Contains(item.Label))
                        continue;
                    labels.Add(item.Label);
                    comboLebal.Items.Add(item.Label);
                }
                //textFileContent.Text = str;
            }
            else
            {
                listLabelRecord = new List<LabelModel>();
                dataGrid.ItemsSource = listLabelRecord;
                //textFileContent.Text = "";
            }
        }

        //c#winform视频播放-一种思路_c# mediaelement 换电脑无法播放视频-CSDN博客  https://blog.csdn.net/wqq1027/article/details/89894072
        //     MymediaElement.UnloadedBehavior = MediaState.Close;
        //MymediaElement.Close();
        //GC.Collect();

        //WPF中设置TEXTBOX为多行文本输入框_wpf 多行文本框-CSDN博客 https://blog.csdn.net/banmuhuangci/article/details/5619420





        private void MediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            // 媒体文件打开时执行的操作
            progressSlider.Maximum = mediaElement.NaturalDuration.TimeSpan.TotalSeconds;
            
            //this.Title = "LaberMedia-"+ new FileInfo(mediaElement.Source.AbsoluteUri).Name;
        }

        private void MediaElement_MediaEnded(object sender, RoutedEventArgs e)
        {
            // 媒体文件播放结束时执行的操作
        }

        private void MediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            // 媒体文件播放失败时执行的操作
        }

        private void buttonPlay_Click(object sender, RoutedEventArgs e)
        {
            if (mediaElement.Source != null)
            {
                mediaElement.Play();
            }
        }

        private void buttonPause_Click(object sender, RoutedEventArgs e)
        {
            if (mediaElement.Source != null)
            {
                mediaElement.Pause();
            }
        }

        private void buttonStop_Click(object sender, RoutedEventArgs e)
        {
            if (mediaElement.Source != null)
            {
                mediaElement.Stop();
            }
        }

        private void progressSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            mediaElement.Position=TimeSpan.FromSeconds(progressSlider.Value);
        }

        private void buttonPre_Click(object sender, RoutedEventArgs e)
        {
            mediaElement.Position = TimeSpan.FromSeconds(mediaElement.Position.TotalSeconds-5);
        }

        private void buttonNext_Click(object sender, RoutedEventArgs e)
        {
            mediaElement.Position = TimeSpan.FromSeconds(mediaElement.Position.TotalSeconds + 5);
        }

        List<LabelModel> listLabelRecord = new List<LabelModel>();
        private void buttonLabel_Click(object sender, RoutedEventArgs e)
        {
            listLabelRecord.Add(new LabelModel() { Time=mediaElement.Position,Label=comboLebal.Text});
            //textFileContent.Text = getLabelRecord();
            listLabelRecord=listLabelRecord.OrderBy(p => p.Time).ToList();
            dataGrid.ItemsSource = listLabelRecord;
            if (!labels.Contains(comboLebal.Text))
            {
                labels.Add(comboLebal.Text);
                comboLebal.Items.Add(comboLebal.Text);
                //comboLebal.ItemsSource = labels;
            }
           
        }
        string getLabelRecord()
        {
            string res = "";
            foreach(var i in listLabelRecord.OrderBy(p => p.Time))
            {
                res += string.Format("[{0}]{1}\n",
                    i.Time.ToString(@"mm\:ss"),
                    i.Label);

            }
            return res;
        }

        private void buttonOpenLabel_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "文本文件(*.txt)|*.txt";
            if (openFileDialog.ShowDialog() == true)
            {
                // 获取选中的文件路径
                string filePath = openFileDialog.FileName;
                // 这里可以进行文件路径的进一步处理
                labelFileName = filePath;
                //if (File.Exists(labelFileName))
                //{
                //    var str = File.ReadAllText(labelFileName);
                //    listLabelRecord = JsonHelper.ParseJson<List<LabelModel>>(str);
                //    dataGrid.ItemsSource = listLabelRecord;
                //}
                LoadRecord();
            }
        }

        private void buttonSaveLabel_Click(object sender, RoutedEventArgs e)
        {
            if(string.IsNullOrEmpty( labelFileName))
                return;
            var str = JsonHelper.Serialize(listLabelRecord);
            File.WriteAllText(labelFileName, str);
        }

        private void buttonSaveAs_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = labelFileName;
            if (saveFileDialog.ShowDialog() == true)
            {
                // 获取选中的文件路径
                string filePath = saveFileDialog.FileName;
                // 这里可以进行文件路径的进一步处理
                labelFileName = filePath;
                buttonSaveLabel_Click(null, null);

            }
        }

        private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
           var idx= dataGrid.SelectedIndex;
            if (idx == -1)
                return;
            var item = listLabelRecord[idx];
            mediaElement.Position = item.Time;
            comboLebal.Text = item.Label;
        }

        private void dataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {

        }

        private void buttonLabelDel_Click(object sender, RoutedEventArgs e)
        {
            var toDel = new List<LabelModel>();
            foreach (var i in dataGrid.SelectedCells)
            {
                var model = i.Item as LabelModel;
                if (!toDel.Contains(model))
                    toDel.Add(model);
            }
            foreach (var i in toDel)
            {
                listLabelRecord.Remove(i);
            }
            dataGrid.ItemsSource = listLabelRecord.ToList();
        }

      
    }

   

   
}
